"""
__author__ = 'berlinyoung'
@File   :base.py
@Date   :2022/5/9 16:49
-*- coding: utf-8 -*-
"""
import yaml
from selenium import webdriver
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait


class Base:
    _base_url = "https://work.weixin.qq.com/wework_admin/loginpage_wx?redirect_uri=https%3A%2F%2Fwork.weixin.qq.com%2Fwework_admin%2Fframe#index"
    with open("../datas/data.yaml", encoding="UTF-8") as f:
        cookies = yaml.safe_load(f)
    '''
    Base提供公共方法的封装，即和页面逻辑无关的封装
    比如解决driver初始化的问题
    '''
    # 添加baseurl，可以支持测试用例灵活配置起始页
    # base完全和业务逻辑耦合
    def __init__(self,base_driver=None):
        if base_driver is None:
            # 通过remote复用浏览器
            opt = webdriver.ChromeOptions()
            # 加入调试地址
            opt.debugger_address = "127.0.0.1:9222"
            # 实例化对象
            self.driver = webdriver.Chrome(options=opt)
            # 打开初始化页面
            self.driver.get(self._base_url)
            cookie = self.driver.get_cookies()
            with open("../datas/data.yaml", "w", encoding="UTF-8") as f:
                yaml.dump(cookie, f)
            for cookie_access in self.cookies:
                self.driver.add_cookie(cookie_access)
            # 隐私等待3秒，解决问题 no such element：Unable to locate element
            self.driver.implicitly_wait(3)
        else:
            self.driver:WebDriver = base_driver

    def find_and_send(self,by,locator = None, text=None):
        if locator is None:

            ele = self.driver.find_element(by[0],by[1])
            return ele.send_keys(by[2])
        else:
            ele = self.driver.find_element(by=by, value=locator)
            return ele.send_keys(text)

    def finds(self,by,locator = None):
        if locator is None:
            return self.driver.find_elements(*by)

        else:
            return self.driver.find_elements(by=by,value=locator)

    def find_and_click(self,by,locator = None):
        if locator is None:
            ele = self.driver.find_element(*by)

        else:
            ele = self.driver.find_element(by=by,value=locator)
        return ele.click()